const utils = require("loader-utils");
const path = require("path");
const mime = require("mime-types");

function getMimetype(resourcePath) {
  return mime.contentType(path.extname(resourcePath));
}

function getEncodedData(content, resourcePath, encoding = "base64") {
  return `data:${getMimetype(resourcePath)}${
    encoding ? `;${encoding}` : ""
  },${content.toString(encoding || undefined)}`;
}

function handlerPath(options, resourcePath, context, url) {
  if (typeof options.outputPath === "function") {
    return options.outputPath(url, resourcePath, context);
  } else {
    return path.posix.join(options.outputPath, url);
  }
}

module.exports = function loader(content, sourcemap, mate) {
  const options = utils.getOptions(this);
  const context = options.context || this.rootContext;
  const name = options.name || "[contenthash:6].[ext]";
  const url = utils.interpolateName(this, name, {
    context,
    content,
    regExp: options.regExp,
  });
  let outputPath = url;
  const resourcePath = this.resourcePath;

  if (options.limit && options.limit < content.length) {
    const buff = Buffer.from(content);
    return `export default ${JSON.stringify(
      getEncodedData(buff, resourcePath)
    )}`;
  } else {
    if (options.outputPath) {
      outputPath = handlerPath(options, resourcePath, content, url);
    }
    this.emitFile(outputPath, content, null, null);

    let publicPath = `__webpack_public_path__ + ${JSON.stringify(outputPath)}`;
    return `export default ${publicPath}`;
  }
};

module.exports.raw = true;
